import { Button, Card, Form, Input, message, Select, Space } from "antd";
import React, { useEffect, useState } from "react";
import { SearchOutlined } from "@ant-design/icons";
import Table, { ColumnsType } from "antd/lib/table";
import {
  reqGetCityOrDistrict,
  reqGetHospitalList,
  reqGetProvince,
  reqUpdateHospitalStatus,
} from "@/api/hospital/hospitalList";
import {
  HospitalListItems,
  ProvinceItems,
} from "@/api/hospital/model/hospitalListType";
import { useNavigate } from "react-router-dom";

export default function HospitalList() {
  //声明回调
  const finish = async () => {
    getHospital();
  };
  const reset = () => {
    getHospital();
  };
  const [form] = Form.useForm();
  const navigate = useNavigate();

  //声明事件回调
  let updateStatus =  (id: string, status: number) => {
    return async () => {
      await reqUpdateHospitalStatus(id, status);
      message.success('操作成功');
      // getHospital();
      let res = hospitalList.map(item => {
        if(item.id === id){
          item.status = status;
        }
        return item;
      })
      setHospitalList(res);
    }
  }

  //声明表格结构
  const columns: ColumnsType<any> = [
    {
      width: 70,
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render: (value) => {
        return <img width={60} src={"data:image/png;base64," + value} alt="" />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render: (value, row) => {
        return row.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (value) => {
        return value.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value) => {
        return value ? "已上线" : "已下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 240,
      fixed: "right",
      render: (value, row, index) => {
        return (
          <Space>
            <Button type="primary" onClick={() => {
              navigate(`/syt/hospital/hospitalList/show/${row.id}`)
            }}>查看</Button>
            <Button type="primary" onClick={() => {
              navigate(`/syt/hospital/hospitalList/schedule/${row.hoscode}`)
            }}>排班</Button>
            <Button type="primary" onClick={updateStatus(row.id, row.status ? 0 : 1)}>{row.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
    },
  ];

  //声明三个状态控制页码相关的数据
  let [current, setCurrent] = useState<number>(1);
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  //声明状态 管理医院列表的数据
  let [hospitalList, setHospitalList] = useState<HospitalListItems>([]);
  //声明状态
  let [loading, setLoading] = useState<boolean>(false);
  //声明状态
  let [province, setProvince] = useState<ProvinceItems>([]);
  //声明状态 管理城市信息
  let [city, setCity] = useState<ProvinceItems>([]);
  //管理区域的信息
  let [district, setDisctrict] = useState<ProvinceItems>([]);
  //管理医院类型
  let [hospitalTypes, setHospitalTypes] = useState<ProvinceItems>([]);

  //声明函数
  let getHospital = async () => {
    //获取表单中的数据
    let data = form.getFieldsValue();
    
    setLoading(true);
    let result = await reqGetHospitalList({ page: current, limit: pageSize, ...data });
    setLoading(false);
    //获取数据
    let { content, totalElements } = result;
    //修改总数
    setTotal(totalElements);
    //更新页面显示的医院信息
    setHospitalList(content);
  };

  //声明 useEffect
  useEffect(() => {
    //声明
    getHospital();
  }, [current, pageSize]);

  //声明 useEffect 获取省份信息
  useEffect(() => {
    let getProvince = async () => {
      //获取省份信息
      let province = await reqGetProvince();
      //设置状态
      setProvince(province);
    };
    getProvince();
  }, []);

  //声明函数  获取城市的信息
  let getCity = async (id: number) => {
    //清空城市列表
    setCity([]);
    setDisctrict([]);
    //修改表单元素的值
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    let city = await reqGetCityOrDistrict(id);
    //设置城市数据
    setCity(city);
  };

  //获取县区的信息
  let getDisctirct = async (id: number) => {
    setDisctrict([]);
    //修改区县的值为 undefined
    form.setFieldsValue({ districtCode: undefined });
    let disctrict = await reqGetCityOrDistrict(id);
    //设置城市数据
    setDisctrict(disctrict);
  };

  //获取医院类型的数据
  useEffect(() => {
    let getHospitalTypes = async () => {
      let types = await reqGetCityOrDistrict(10000);
      //更新状态
      setHospitalTypes(types);
    };

    getHospitalTypes();
  }, []);

  return (
    <Card>
      {/* 表单筛选 start */}
      <Form
        name="basic"
        layout="inline"
        onFinish={finish}
        form={form}
        onReset={reset}
      >
        <Form.Item name="provinceCode">
          <Select
            style={{ width: "200px", marginBottom: "20px" }}
            placeholder="请选择省份"
            onChange={getCity}
          >
            {province.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="cityCode">
          <Select
            style={{ width: "200px" }}
            placeholder="请选择市"
            onChange={getDisctirct}
          >
            {city.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="districtCode">
          <Select style={{ width: "200px" }} placeholder="请选择区">
            {district.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype">
          <Select style={{ width: "200px" }} placeholder="医院类型">
            {hospitalTypes.map((item) => {
              return (
                <Select.Option key={item.id} value={item.value}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="status">
          <Select style={{ width: "200px" }} placeholder="医院状态">
            <Select.Option value="1">已上线</Select.Option>
            <Select.Option value="0">已下线</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Space size="middle">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>

            <Button htmlType="reset">清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表单筛选 end */}

      {/* 表格部分 start */}
      <Table
        loading={loading}
        columns={columns}
        dataSource={hospitalList}
        bordered
        rowKey={"id"}
        scroll={{ x: 1300 }}
        pagination={{
          //总数
          total: total,
          //每页显示的数量
          pageSize: pageSize,
          //当前的页码数
          current: current,
          //显示每页显示数量
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10, 20],
          //快速跳转
          showQuickJumper: true,
          //
          showTotal: (total) => {
            return `总计: ${total} 条`;
          },
          //绑定事件
          onChange: (page: number, pageSize: number) => {
            //更新状态
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      />
      {/* 表格部分 end */}
    </Card>
  );
}
